import axios from "axios";
import router from "@/router";

const request = axios.create({
    baseURL: "http://localhost:8081",
    timeout: 300000
})

// request拦截器
request.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8';
    const user = JSON.parse(localStorage.getItem("honey-user") || '{}');
    config.headers['token'] = user.token;

    return config;
}, error => {
    console.error('request error:', error);
    return Promise.reject(error);
});

// response拦截器
request.interceptors.response.use(
    response => {
        let res = response.data;

        // 兼容服务器返回的字符串数据
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res;
        }

        if (res.code === '401') {
            router.push('/login');
        }

        return res;
    },
    error => {
        console.error('request error:', error);
        return Promise.reject(error);
    }
)

export default request;